package hibernate.method;

import hibernate.method.interfaces.AssortmentMethodsInterface;
import hibernate.model.Assortment;
import hibernate.model.Game;
import hibernate.model.Local;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;

public class AssortmentMethods implements AssortmentMethodsInterface{

	@Override
	public void add_items(SessionFactory sessionFactory, Session session,
			Assortment a, int items) {
		a.setItems(items);
		
	}

	@Override
	public void delete_items(SessionFactory sessionFactory, Session session,
			Assortment a, int deleted_items) {
		// TODO Auto-generated method stub
		
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Local> listLocalsByGame(SessionFactory sessionFactory,
			Session session, int game_id) {
		Criteria cr = session.createCriteria(Assortment.class);
		Criterion game = Restrictions.eq("game_id", game_id);
		cr.add(game);
		List<Assortment> ass = new ArrayList<Assortment>(cr.list());
		List <Local> loc = new ArrayList<Local>();
		LocalMethods lm = new LocalMethods();
		for (Assortment a :ass){
			Local l = lm.findLocalById(sessionFactory, session, a.getLocal_id());
			loc.add(l);
		}
		
		return loc;
	}

	@SuppressWarnings("rawtypes")
	@Override
	public int getItemsByLocalAndGame(SessionFactory sessionFactory,
			Session session, int game_id, int local_id) {
		Query query = session.createSQLQuery(
				"select items from assortment a where (a.game_id = :game_id and a.local_id = :local_id)")
				.setParameter("game_id", game_id)
				.setParameter("local_id", local_id);
				List result = query.list();
				return (Integer) result.get(0);
		}

	@SuppressWarnings("unchecked")
	@Override
	public List<Game> listAvailableGamesInLocal(SessionFactory sessionFactory,
			Session session, int local_id) {
		Criteria cr = session.createCriteria(Assortment.class);
		cr.add(Restrictions.eq("local_id", local_id));
		List<Assortment> lista = new ArrayList<Assortment>(cr.list());
		GameMethods gm = new GameMethods();
		List <Game> games = new ArrayList<Game>();
		for (Assortment a : lista){
			if(a.getItems()>0){
				games.add(gm.idToGame(sessionFactory, session, a.getGame_id()));
			}
		}
		return games;
	}

	@Override
	public void add(SessionFactory sessionFactory, Session session,
			int local_id, int game_id, int items) {
		Assortment a = new Assortment();
		a.setLocal_id(local_id);
		a.setGame_id(game_id);
		a.setItems(items);
		session.save(a);
		}

}
